<template>
  <div class="setting-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>个人设置</el-breadcrumb-item>
        </el-breadcrumb>
      </div>

      <div>
        <el-row :gutter="40">
          <el-col :span="16">
            <el-form ref="form" :model="user" label-width="100px">
              <el-form-item label="编号">
                {{ user.id }}
              </el-form-item>
              <el-form-item label="手机">
                {{ user.mobile }}
              </el-form-item>
              <el-form-item label="媒体名称">
                <el-input v-model="user.name"></el-input>
              </el-form-item>
              <el-form-item label="媒体介绍">
                <el-input type="textarea" v-model="user.intro"></el-input>
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="user.email"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="onUpdateUser">保存</el-button>
              </el-form-item>
            </el-form>
          </el-col>
          <el-col class="image-up" :span="8">
            <label for="file">
            <div class="block"><el-avatar :size="150" :src="user.photo"></el-avatar></div>
            </label>
              <div>
              <el-button @click="$refs.file.click()" size="small" type="primary">点击修改</el-button>
            </div>
            <input type="file" ref="file" id="file" @change="onFileChange" hidden>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <el-dialog
      title="修改头像"
      :visible.sync="dialogVisible"
      append-to-body
      width="30%"
      @opened="onDialogOpened"
      @closed="onDialogClosed"
    >
      <div class="preview-image-wrap">
        <vueCropper
          style="width:100%;height:300px"
          ref="cropper"
          :img="previewImage"
          :autoCrop="options.autoCrop"
          :fixedBox="options.fixedBox"
          :canMoveBox="options.canMoveBox"
          :autoCropWidth="options.autoCropWidth"
          :autoCropHeight="options.autoCropHeight"
          :centerBox="options.centerBox"
          @realTime="realTime"
        >

        </vueCropper>
        <!--<img
          class="preview-image"
          :src="previewImage"
          ref="preview-image"
        >-->
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          :loading="updatePhotoLoading"
          @click="onUpdatePhoto"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getUserProfile, updateUserPhoto, updateUserProfile } from '@/api/user'
import globalBus from '@/utils/global-bus'
export default {
  name: 'SettingIndex',
  data () {
    return {
      user: {
        id: null,
        email: '',
        intro: '',
        mobile: '',
        name: '',
        photo: ''
      },
      options: {
        autoCrop: true, // 默认生成截图框
        fixedBox: false, // 固定截图框大小
        canMoveBox: true, // 截图框不能拖动
        autoCropWidth: 200, // 截图框宽度
        autoCropHeight: 200, // 截图框高度
        centerBox: false // 截图框被限制在图片里面
      },
      previews: {}, // 实时预览图数据
      dialogVisible: false, // 控制上传图片裁切预览的显示状态
      previewImage: '', // 预览图片
      cropper: null, // 裁切器示例
      updatePhotoLoading: false, // 更新用户头像 loading 状态
      updateProfileLoading: false // 更新基本信息的 loading 状态
    }
  },
  methods: {
    // 实时预览
    realTime (data) {
      this.previews = data
    },
    loadUser () {
      getUserProfile().then(res => {
        this.user = res.data.data
      })
    },
    onFileChange () {
      const file = this.$refs.file
      const blobData = window.URL.createObjectURL(file.files[0])

      this.previewImage = blobData

      // 展示弹出层，预览用户选择的图片
      this.dialogVisible = true

      // 解决选择相同文件不触发 change 事件问题
      this.$refs.file.value = ''
    },
    onDialogOpened () {
      this.dialogVisible = true
    },
    onDialogClosed () {
      this.dialogVisible = false
    },
    onUpdatePhoto () {
      // 让确定按钮开始 loading
      this.updatePhotoLoading = true
      // 获取裁切的图片对象
      this.$refs.cropper.getCropBlob(res => {
        // res是裁剪后图片的bolb对象
        var fd = new FormData()
        fd.append('photo', res)
        // console.log(res)
        updateUserPhoto(fd).then(resp => {
          // console.log(resp)
          // 关闭对话框
          this.dialogVisible = false
          // 关闭确定按钮的 loading
          this.updatePhotoLoading = false

          this.$message({
            type: 'success',
            message: '更新头像成功'
          })
          // 更新顶部登录用户的信息
          this.user.photo = resp.data.data.photo
          // 更新顶部登录用户的信息
          globalBus.$emit('update-user', this.user)
        }, () => {
          this.$message({
            type: 'error',
            message: '更新头像失败，请检查网络！'
          })
          this.updatePhotoLoading = false
        })
      })
    },
    onUpdateUser () {
      // 表单验证
      // 验证通过，提交表单

      // 开启 loading 状态
      this.updateProfileLoading = true
      const { name, intro, email } = this.user
      updateUserProfile({
        name,
        intro,
        email
      }).then(res => {
        this.$message({
          type: 'success',
          message: '保存成功'
        })

        // 关闭 loading 状态
        this.updateProfileLoading = false

        // 更新头部当前登录用户的信息
        // 发布通知，用户信息已修改
        globalBus.$emit('update-user', this.user)
      })
    }
  },
  components: {},
  props: {},
  computed: {},
  watch: {},
  created () {
    this.loadUser()
  },
  mounted () {
  },
  beforeDestroy () {}
}
</script>

<style scoped lang='less'>
.block{
  display: flex;
  justify-content: center;
  align-items: center;
}
.image-up{
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding-top: 20px;
  div{
    padding-bottom: 35px;
  }
}
.preview-image-wrap {
  .preview-image {
    display: block;
    max-width: 100%;
    height: 200px;
  }
}
</style>
